package top.xizai.wrr.wrr.impl;

import lombok.Data;
import top.xizai.wrr.Element;
import top.xizai.wrr.wrr.IWrr;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @NAME: WSC
 * @DATE: 2021/12/27
 * @DESCRIBE:
 **/
public class WrrSmooth implements IWrr {

    private final Wrr[] wrrs;
    private final int total;

    public WrrSmooth(Element[] elements) {
        wrrs = Arrays.stream(elements)
                        .map(Wrr::new)
                        .collect(Collectors.toList())
                        .toArray(new Wrr[0]);

        total = Arrays.stream(elements)
                        .mapToInt(Element::getWeight)
                        .sum();
    }

    @Data
    class Wrr {
        Element element;
        int current = 0;

        public Wrr(Element element) {
            this.element = element;
        }
    }

    /**
     * 平滑轮序算法
     * @return
     */
    @Override
    public String next() {
        Wrr max = null;

        for (int i = 0; i < wrrs.length; i++) {
            var wrr = wrrs[i];
            wrr.setCurrent(wrr.getElement().getWeight() + wrr.getCurrent());

            if (max == null || wrr.getCurrent() > max.getCurrent()) {
                max = wrr;
            }
        }

        max.setCurrent(max.getCurrent() - total);
        return max.getElement().getPeer();
    }
}
